package com.yugao.fintech.draper.security.support;

import cn.hutool.core.util.ArrayUtil;
import com.yugao.fintech.draper.security.SecurityUser;
import com.yugao.fintech.draper.security.util.SecurityUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.Objects;

@Slf4j
public class PermissionService {
    /**
     * 判断是否有权限
     *
     * @param permission 权限
     * @return 是否
     */
    public boolean hasPermission(String permission) {
        return hasAnyPermissions(permission);
    }

    /**
     * 判断是否有权限，任一一个即可
     *
     * @param permissions 权限
     * @return 是否
     */
    public boolean hasAnyPermissions(String... permissions) {
        // 如果为空 说明有权限
        if (ArrayUtil.isEmpty(permissions)) {
            return true;
        }

        // 获得当前登录的角色 如果为空 说明没有权限
        SecurityUser user = SecurityUserUtil.getCurrentUser();
        if (Objects.isNull(user)) {
            return false;
        }

        Collection<? extends GrantedAuthority> authorities = SecurityUserUtil.getAuthorities();
        return authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .filter(StringUtils::hasText)
                .anyMatch(x -> PatternMatchUtils.simpleMatch(permissions, x));
    }
}
